package ss.lianft.auth;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import ss.lianft.model.Func;
import ss.lianft.model.FuncOrg;
import ss.lianft.model.User;
import ss.lianft.model.UserOrg;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户登录及权限验证类
 */
public class UserRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(UserRealm.class);
    @Autowired
    private SQLManager sqlManager;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String)getAvailablePrincipal(principalCollection);
        logger.info("用户"+username+"权限验证装备:");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user =new User();
        user.setUsername(username);
        user = sqlManager.selectSingle("user.list",user,User.class);
        //角色装配
        UserOrg uoQuery = new UserOrg();
        uoQuery.setUserId(user.getId());
        List<UserOrg> uos = sqlManager.select("userOrg.list",UserOrg.class,uoQuery);
        List<Func> funcs = new ArrayList<Func>();
        for(UserOrg uo : uos){
            info.addRole(String.valueOf(uo.getOrgId()));
            FuncOrg foQuery = new FuncOrg();
            foQuery.setOrgId(uo.getOrgId());
            List<FuncOrg> fos = sqlManager.select("funcOrg.list",FuncOrg.class,foQuery);
            for(FuncOrg fo : fos){
                info.addStringPermission(String.valueOf(fo.getFuncId()));
            }
        }
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = authenticationToken.getPrincipal().toString();
        logger.info("用户"+username+"登录操作:");
        User currentUser = new User();
        currentUser.setUsername(username);
        currentUser = sqlManager.selectSingle("user.list",currentUser,User.class);
        if(currentUser ==null){
            throw new UnknownAccountException("用户不存在!");
        }
        //Salt define
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,currentUser.getPassword(),credentialsSalt,getName());

        return info;
    }
}
